<template>
	<section>
		<!--工具条 高级查询-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.name" placeholder="姓名"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="getQuery" >查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
    <el-table :data="departments" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="sn" label="部门编号" width="120" sortable>
      </el-table-column>
      <el-table-column prop="name" label="部门名称" width="120" sortable>
      </el-table-column>
      <el-table-column prop="manager.username" label="部门经理" width="120" sortable>
      </el-table-column>
      <el-table-column prop="parent.name" label="上级部门"  width="120" sortable>
      </el-table-column>
      <el-table-column prop="state" label="状态"width="120" sortable>
        <template slot-scope="scope" >
          <span style="color: green" v-if="scope.row.state==1">启用</span>
          <span style="color: red" v-else-if="scope.row.state==0">停用</span>
        </template>
      </el-table-column>


      <el-table-column label="操作" width="150">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)" v-perm="'department:save2update'">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)" v-perm="'department:delete'">删除</el-button>
        </template>
      </el-table-column>

    </el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination
          background
          layout="prev, pager, next"
          @current-change="handleCurrentChange"
          :page-size="pageSize"
          :total="totals"
          style="float:right;">
      </el-pagination>
		</el-col>

		<!--编辑和添加界面-->
		<el-dialog :title="title" :visible.sync="editFormVisible" :close-on-click-modal="false">
			<el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
				<el-form-item label="部门编号" prop="sn">
					<el-input v-model="editForm.sn" auto-complete="off"></el-input>
				</el-form-item>
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="editForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="部门状态">
          <el-radio-group v-model="editForm.state">
            <el-radio class="radio" :label="1">启用</el-radio>
            <el-radio class="radio" :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="部门经理" prop="managerId">
<!--          <el-input v-model="editForm.managerId" auto-complete="off"></el-input>-->
          <el-select  clearable v-model="editForm.managerId" filterable placeholder="请选择">
            <el-option
                v-for="item in employees"
                :label="item.username"
                :value="item.id">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
            </el-option>
          </el-select>

        </el-form-item>
        <el-form-item label="上级部门" prop="parentId">
<!--          <el-input v-model="editForm.parentId" auto-complete="off"></el-input>-->
          <el-cascader v-model="editForm.parentId"
              :options="deptTree"
              :props="{
                checkStrictly: true ,
                label:'name',// 级联框显示那个属性的值
                value: 'id'    // 回显时需要,回传值的时候也需要
              }"
              clearable>

          </el-cascader>
        </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>


	</section>
</template>

<script>
	export default {
		data() {
			return {

        title:'',// 动态显示编辑和新增的title
				filters: {
					name: ''  //高级查询所需数据
				},
        deptTree:[],// 部门树
        employees:[],//保存所有的员工表，为了新增和编辑部门经理回显
				departments: [],
				totals: 0, // 数据的总数
				currentPage: 1, // 当前页
        pageSize:5, // 每页显示条数
				listLoading: false, // 忙等框
				sels: [], //列表选中列
				editFormVisible: false,//编辑界面是否显示
				editLoading: false, // 模态框默认关闭
				editFormRules: {  // 空值校验
          sn: [
            { required: true, message: '请输入部门编号', trigger: 'blur' }
          ],
          name: [
						{ required: true, message: '请输入部门名称', trigger: 'blur' }
					]
				},
				//编辑界面数据
				editForm: {
					id: null,
					sn:'',
          name: '',
					state: null,
					managerId: null,
					parentId: null,
				}
      }
		},
		methods: {
      //获取部门树 - 无线级联
      getDeptTree(){
          this.$http.get("/department/deptTree").then(res=>{
            this.deptTree = res.data;
          })

      },

      // 获取部门经理
      getEmployees(){
        this.$http.get("/employee").then(res=>{
            this.employees = res.data;
        });
      },
      // 高级查询从第一页开始查询
      getQuery(){
            this.currentPage = 1,
            this.getDepartments()
      },
		  // 分页显示
			handleCurrentChange(currentPage) {
				this.currentPage = currentPage;
				this.getDepartments();
			},
			//获取部门列表
			getDepartments() {
				let para = {
          currentPage: this.currentPage,
					pageSize:this.pageSize,
          keyword: this.filters.name  // 高级查询需要的
				};
        // 开启忙等框
				this.listLoading = true;
				this.$http.post("/department",para).then(res=>{
          // 关闭忙等框
          this.listLoading = false;
          this.departments = res.data.data;
          this.totals = res.data.totals;
        }).catch(res=>{
          this.$message.error("系统繁忙，请骚后重试！！！！")


        })
			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => { // 点击确认执行操作
					this.listLoading = true;  // 开启忙等框
          // 发送删除请求
					this.$http.delete("/department/"+ row.id).then(res=>{
              // 关闭忙等框
              this.listLoading = false;
              if(res.data.success){
                  // 删除成功
                 this.$message({
                   message: '删除成功',
                   type: 'success'})
               }else {
                  // 删除失败
                 this.$message({
                   message: '删除失败',
                   type: 'error'})
               }

               // 重新刷新页面
              this.getDepartments();
          }).catch(res=>{
            // 删除失败
            this.$message({
              message: res.data.message,
              type: 'error'})
          })
				}).catch(() => { // 点击取消后不执行操作

				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
        this.getDeptTree(); // 点击编辑加载上级部门树
        this.getEmployees(); // 点击编辑加载部门经理
        this.title = "编辑";
				this.editFormVisible = true; // 开启模态框
				this.editForm = Object.assign({}, row);
			},
			//显示新增界面
			handleAdd: function () {
        this.getDeptTree(); // 点击编辑加载上级部门树
        this.getEmployees(); // 点击编辑加载部门经理
        this.title = "新增";
				this.editFormVisible = true; // 开启模态框
			  // 添加清空模态框数据
				this.editForm = {
          id: null,
          sn:'',
          name: '',
          state: 1,
          managerId: null,
          parentId: null
				};
			},
			//编辑和添加 的提交按钮
			editSubmit: function () {
				this.$refs.editForm.validate((valid) => {
					if (valid) {
            this.$confirm('确认提交吗？', '提示', {}).then(() => {
							// 开启忙等框
              this.editLoading = true;

              // 克隆表单中的数据 赋值给para
							let para = Object.assign({}, this.editForm);
              // console.log(para.parentId[para.parentId.length-1])
              let arr = para.parentId;
              if(arr &&  arr.length==0){
                para.parentId =null;
              }
              if(arr && arr.length > 0){
                // 后台通过Long接收
                para.parentId=arr[arr.length-1];
              }

              // 发送 请求
              this.$http.put("/department",para).then(res=>{
                // 关闭忙等框
                this.editLoading = false;
                if (res.data.success){
                  this.$message({
                    message: '操作成功',
                    type: 'success'
                  });
                }else {
                  this.$message({
                    message: res.data.message,
                    type: 'error'
                  });
                }
                // 关闭模态框
                this.editFormVisible = false;
                // 重新刷新页面
                this.getDepartments();
              }).catch(res=>{
                this.$message({
                  message: '系统异常，骚后重试',
                  type: 'error'
                });
              })
						});
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id);
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
				// 发送批量删除请求
          this.$http.patch("/department",ids).then(res=>{
            // 关闭忙等框
            this.listLoading = false;
            if (res.data.success){
              this.$message({
                message: '删除成功',
                type: 'success'
              });
            }else {
              this.$message({
                message: res.data.message,
                type: 'error'
              });
            }
            // 重新发送刷新页面请求
            this.getDepartments();
          }).catch(res=>{
            this.$message({
              message: '系统异常，骚后重试',
              type: 'error'
            });

          })


				}).catch(() => {

				});
			}
		},
		mounted() {
			this.getDepartments();


		}
	}

</script>

<style scoped>

</style>